//
//  OrderViewController.m
//  xpkc
//
//  Created by TopSageMacMini on 14/12/19.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "OrderViewController.h"
#import "OrderCell.h"
#import "OrderInfoViewController.h"
#import "UserMessage.h"
#import "orderlistModel.h"
#import "MBProgressHUD.h"

#import "TiyonOrderCell.h"

@interface OrderViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *_tableView;
    NSMutableArray *_dataArray;
    BOOL isFree;    // 记录否有赠送课程
    NSArray * course;
    NSArray * orderNum;
   
}
@end

@implementation OrderViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.navigationItem.title = @"全部订单";
        [self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                 [UIColor colorWithRed:255/255.0f green:159/255.f blue:0/255.f alpha:1], NSForegroundColorAttributeName,
                                                 nil] forState:UIControlStateSelected];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = NO;
    _dataArray = [[NSMutableArray alloc] init];
    [self createTableView];
    [self createData];
}

-(void)createData
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中";
    //获取数据
    NSString *module = @"user";
    NSString *interface = @"orderlist";
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    NSDictionary *parameter = @{@"time":timeString,@"uid":[UserMessage sharedUserMessage].userMid};
    //POST请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([[dic objectForKey:@"info"] isKindOfClass:[NSString class]]) {
            [self showAlertWithMessage:@"暂无订单"];
        }else{
            orderNum=[dic objectForKey:@"info"];
            for (NSDictionary * info in orderNum) {
                orderlistModel * model =[[orderlistModel alloc] init];
                model.oid=[info objectForKeyedSubscript:@"oid"];
                model.priceCount=[info objectForKey:@"priceCount"];
                model.state=[NSString stringWithFormat:@"%@",[info objectForKey:@"state"]];
                model.course=[info objectForKey:@"course"];
                
                
            
                
                [_dataArray addObject:model];
            }
            
            
            [_tableView reloadData];
            
            
        }
        [hud hide:YES];
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        logdebug(@"%@",error.localizedDescription);
        [hud hide:YES];
    }];
    
}
- (void)showAlertWithMessage:(NSString *)message {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
}
- (void)createTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
}

#pragma mark =======tableView Delegate & dataSource=========
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    
    CGFloat oneOrderH = 60;
    orderlistModel * model =_dataArray[indexPath.row];
    int arrayCount = model.course.count;
    return 100 + oneOrderH * arrayCount + 40;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return orderNum.count;
    //这里返回数组数量
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellId = @"myCell";
    TiyonOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if(!cell) {
        cell = [[TiyonOrderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    orderlistModel * model =_dataArray[indexPath.row];
    [cell configWithOrderModel:model];
    
    cell.payButton.tag = indexPath.row;
    cell.chexiaoButton.tag=indexPath.row;
    [cell.payButton addTarget:self action:@selector(payClick:) forControlEvents:UIControlEventTouchUpInside];
    [cell.chexiaoButton addTarget:self action:@selector(cheClick:) forControlEvents:(UIControlEventTouchUpInside)];
//    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}
-(void)cheClick:(UIButton *)btn
{
    
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
     orderlistModel * model =_dataArray[btn.tag];
    NSString *module = @"order";
    NSString *interface = @"cancelorder";
    
    NSString *timeString = [GetTime getTime];
    NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
    NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
    
    NSDictionary *parameter = @{@"time":timeString,@"mid":[UserMessage sharedUserMessage].userMid,@"oid":model.oid};
    NSLog(@"%@",parameter);
    //POST请求
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@---",dic);
        NSLog(@"%@",[dic objectForKey:@"info"]);
        [_tableView reloadData];
        [hud hide:YES];
      
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"shibai");
        [hud hide:YES];
    }];

    
}
-(void)payClick:(UIButton *)btn{
    
    OrderInfoViewController *VC = [[OrderInfoViewController alloc] init];
    VC.hidesBottomBarWhenPushed = YES;
    orderlistModel * model =_dataArray[btn.tag];
    VC.oid=model.oid;
    VC.aid=model.aid;
    VC.ordelModel = model;
    [self.navigationController pushViewController:VC animated:YES];
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderInfoViewController *VC = [[OrderInfoViewController alloc] init];
    VC.hidesBottomBarWhenPushed = YES;
    orderlistModel * model =_dataArray[indexPath.row];
    VC.oid=model.oid;
    VC.aid=model.aid;
    VC.ordelModel = model;
    [self.navigationController pushViewController:VC animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}



@end
